<?php

namespace app\api\controller;

use app\admin\model\cooperation\Apply;
use app\admin\model\Suggestion;
use app\admin\model\user\Balance;
use app\admin\model\user\Extend;
use app\common\controller\Api;
use app\common\library\ThirdDianping;
use app\common\library\Ems;
use app\common\library\Sms;
use Carbon\Carbon;
use EasyWeChat\Factory;
use fast\Http;
use fast\Random;
use think\Config;
use think\Db;
use think\Env;
use think\Exception;
use think\Validate;
use app\common\model\Third;
use app\common\library\Faceid as FaceIdLib;
use app\common\library\Credit as CreditLib;


/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'applyCooperation', 'applySuggestion'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    public function exchangeDZMT()
    {
        $user = $this->auth->getUser();

        if (in_array($user->group_id, [2, 3])) {
            $this->error('你好，暂时不能兑换，请通过美团平台直接申请退款');
        }

        $userId = $user->id;


        $code = $this->request->get('code');
        $code = str_replace(' ', '', $code);
        $dianping = new ThirdDianping();
        $result = $dianping->prepare($code);

        if (200 == $result['code']) {
            $dealGroupId = $result['data']['result'][0]['dealGroupId'];
            $dealGroupTitle = $result['data']['result'][0]['dealTitle'];
            if (empty($dealGroupId)) {
                $this->error('没有找到团券对应的小程序卡券，请联系管理员处理');
            } else {
                $card = \app\common\model\Card::where('dzmt_dealgroupid', $dealGroupId)->find();
                if (!$card) {
                    $this->error('没有找到团券对应的小程序卡券，请联系管理员处理');
                }
            }
        } else {
            $this->error($result['msg']);
        }

        //判断是否超过了此卡的购买次数限制
        if ($card->could_buy_number) {
            $alreadyCouldNumber = \app\admin\model\user\Card::where('user_id', $userId)
                ->where('card_id', $card->id)
                ->count();

            if ($alreadyCouldNumber >= $card->could_buy_number) {
                $this->error("对不起，此卡有购买次数限制，你已经购买过{$alreadyCouldNumber}次");
            }
        }

        $result = $dianping->exchange($code);

        if (200 == $result['code']) {

            \app\admin\model\user\Card::create([
                'user_id' => $userId,
                'card_id' => $card->id,
                'name' => $card->card_name,
                'type' => $card->card_type,
                'price' => $card->card_price,
                'service_start' => Carbon::now()->toDateTimeString(),
                'service_end' => Carbon::now()->addDays($card->card_service_term_day)->toDateTimeString(),
                'store_ids' => $card->store_ids,
//                'room_id' => $card->room_id,
//                'checknum' => $card->card_checknum,
//                'max_hour' => $card->card_max_hour,
                'total_hour' => $card->card_total_hour,
                'pay_way' => 1, // 大众美团兑换
                'dzmt' => serialize($result['data']),
                'dzmt_code' => $code,
                'createtime' => time(),
                'updatetime' => time()
            ]);

            $this->success('ok', ['group_title' => $dealGroupTitle]);

        } else {
            $this->error($result['msg']);
        }
    }

    public function getUserCardDetail()
    {
        $userId = $this->auth->getUser()->id;
        $cardId = $this->request->get('id');

        $card = \app\admin\model\user\Card::where('id', $cardId)
            ->find();

        // $rooms = \app\admin\model\Room::all();
        // 增加房间状态过滤
        $rooms = \app\admin\model\Room::where('status', 'normal')->select();
        // 所有门店的教室ID集合
        $store2RoomIds = [];
        // 所有教室对应的门店ID
        $room2StoreIds = [];
        foreach ($rooms as $r) {
            $room2StoreIds[$r->id] = $r->store_id;
            if (!isset($store2RoomIds[$r->store_id])) {
                $store2RoomIds[$r->store_id] = [];
            }
            $store2RoomIds[$r->store_id][] = $r->id;
        }
        // 所有门店ID
        $stores = \app\common\model\Store::all();
        $storeIds = array_map(function ($e) {
            return $e['id'];
        }, $stores);

        // 设置的教室
        $setRoomIds = explode(',', $card->store_ids);
        // 设置的门店
        $setStoreIds = [];
        // 相关门店的教室总数
        $totalRoom = 0;
        foreach ($setRoomIds as $rId) {
            if (isset($room2StoreIds[$rId]) && !in_array($room2StoreIds[$rId], $setStoreIds)) {
                $setStoreIds[] = $room2StoreIds[$rId];
                $totalRoom += count($store2RoomIds[$room2StoreIds[$rId]]);
            }
        }
        $countRoom = count($setRoomIds);
        $countStore = count($setStoreIds);

        if ($totalRoom == $countRoom) {
            $card->display_room_name = '全教室通用';
        } else {
            $card->display_room_name = "适用${countRoom}个教室";
        }
        if ($countStore == count($storeIds)) {
            $card->display_store_name = '适用全部门店';
        } else {
            $card->display_store_name = "适用${countStore}家门店";
        }

        // 教室列表 
        $rooms = \app\admin\model\Room::where('status', 'normal')->with('store')->select();
        $roomIds = array_map(function ($e) {
            return $e['id'];
        }, $rooms);

        $roomNameMap = [];
        foreach ($rooms as $v) {
            $roomNameMap[$v['id']] = $v['store']['store_name'] . ' - ' . $v['room_name'];
        }
        $setRoomIds = explode(",", $card->store_ids);
        $count = count($setRoomIds);
        $roomsList = [];
        if ($countStore == count($storeIds) && $count == count($roomIds)) {
            $card->room_list_string = '适用全部教室';
            $roomsList[] = '适用全部教室';
        } else {
            $card->room_list_string = '';

            $ids = explode(',', $card->store_ids);
            foreach ($ids as $v) {
                if (isset($roomNameMap[$v])) {
                    $card->room_list_string .= $roomNameMap[$v] . "\n";
                    $roomsList[] = $roomNameMap[$v];
                }
            }
        }
        $card->rooms_list = $roomsList;


        $consume = \app\admin\model\Reserve::with(['store', 'room'])
            ->where('card_id', $cardId)
            ->where('pay_way', 1)
            ->where('re_status', 1)
            ->select();

        $consume = array_map(function ($e) {
            $e->reserve_time = Carbon::parse($e->starttime)->format('Y/m/d H:i') .' - '. Carbon::parse($e->endtime)->format('H:i');
            $e->display_store_name = $e->store->store_name;
            $e->display_room_name = $e->room->room_name;
            return $e;
        }, $consume);

        $this->success('ok', [
            'card' => $card,
            'consume_list' => $consume,
        ]);
    }

    public function getMyCards()
    {
        $userId = $this->auth->getUser()->id;
        $cards = \app\admin\model\user\Card::where('user_id', $userId)
            ->order('id', 'desc')
            ->select();

        // $rooms = \app\admin\model\Room::all();
        // 增加房间状态过滤
        $rooms = \app\admin\model\Room::where('status', 'normal')->select();
        // 所有门店的教室ID集合
        $store2RoomIds = [];
        // 所有教室对应的门店ID
        $room2StoreIds = [];
        foreach ($rooms as $r) {
            $room2StoreIds[$r->id] = $r->store_id;
            if (!isset($store2RoomIds[$r->store_id])) {
                $store2RoomIds[$r->store_id] = [];
            }
            $store2RoomIds[$r->store_id][] = $r->id;
        }
        // 所有门店ID
        $stores = \app\common\model\Store::all();
        $storeIds = array_map(function ($e) {
            return $e['id'];
        }, $stores);

        $cards = array_map(function ($e) use ($storeIds, $store2RoomIds, $room2StoreIds) {
            // 设置的教室
            $setRoomIds = explode(',', $e->store_ids);
            // 设置的门店
            $setStoreIds = [];
            // 相关门店的教室总数
            $totalRoom = 0;
            foreach ($setRoomIds as $rId) {
                if (isset($room2StoreIds[$rId]) && !in_array($room2StoreIds[$rId], $setStoreIds)) {
                    $setStoreIds[] = $room2StoreIds[$rId];
                    $totalRoom += count($store2RoomIds[$room2StoreIds[$rId]]);
                }
            }
            $countRoom = count($setRoomIds);
            $countStore = count($setStoreIds);

            if ($totalRoom == $countRoom) {
                $e->display_room_name = '全教室通用';
            } else {
                $e->display_room_name = "适用${countRoom}个教室";
            }
            if ($countStore == count($storeIds)) {
                $e->display_store_name = '适用全部门店';
            } else {
                $e->display_store_name = "适用${countStore}家门店";
            }

            return $e;
        }, $cards);
        $newCards = [];
        foreach ($cards as $v) {
            if ($v->hasconsumedhour < $v->total_hour) {
                $newCards[] = $v;
            }
        }

        $this->success('ok', $newCards);
    }

    public function getUserBalancePage()
    {
        $userId = $this->auth->getUser()->id;
        $money = Extend::where('user_id', $userId)->find()->balance;

        $stores = \app\common\model\Store::all();
        $storesMap  = [];
        foreach ($stores as $store) {
            $storesMap[$store->id] = $store->store_name;
        }

        $rooms = \app\common\model\Room::all();
        $roomsMap = [];
        foreach ($rooms as $room) {
            $roomsMap[$room->id] = $room->room_name;
        }

        $balances = Balance::with(['paytransaction'])->where('fa_user_balance.user_id', $userId)->order('id', 'desc')->select();
        $recharge = [];
        $consume = [];

        foreach ($balances as $balance) {
            if (1 == $balance->type or 2 == $balance->type) {
                $recharge[] = [
                    'charge_type' => $balance->type,
                    'fee' => $balance->value,
                    'time' => Carbon::createFromTimestamp($balance->createtime)->format('Y/m/d H:i'),
                    'order_num' => 2 == $balance->type ? '-' : $balance->paytransaction->out_trade_no,
                ];
            }
        }

        // 因为2个库并行引出的bug
        $sql = 'SELECT * FROM `fa_reserve` as r left join `fa_user_balance` as b on b.id = r.balance_id WHERE r.user_id = '.$userId.';';
        $kk = Db::query($sql);
        foreach ($kk as $item) {
            $consume[] = [
                'fee' => $item['value'],
                'store' => $storesMap[$item['store_id']],
                'room' => $roomsMap[$item['room_id']],
                'reserve_time' => Carbon::parse($item['starttime'])->format('Y/m/d H:i') .' - '.
                    Carbon::parse($item['endtime'])->format('H:i'),
                'order_time' => Carbon::createFromTimestamp($item['createtime'])->format('Y/m/d H:i')
            ];
        }

        $this->success('ok', [
            'balance' => $money,
            'charge_list' => $recharge,
            'consume_list' => $consume
        ]);
    }

    public function getDirectPayOrder()
    {
        $userId = $this->auth->getUser()->id;
        $orders = \app\admin\model\Reserve::with(['paytransaction', 'room', 'store'])
            ->where('reserve.user_id', $userId)
            ->where('pay_way', 3) // 3=直接微信支付
            ->select();

        $orders = array_map(function ($e) {
            $e->room->room_bannerimage = ykxImageUrl($e->room->room_bannerimage);
            $e->formatDate = Carbon::parse($e->starttime)->format('Y/m/d');
            $e->formatstart = Carbon::parse($e->starttime)->format('H:i');
            $e->formatend = Carbon::parse($e->endtime)->format('H:i');
            $e->formatOrderTime = Carbon::createFromTimestamp($e->createtime)->format('Y/m/d H:i');
            if (2 == $e->re_status) {
                $e->status = 5; //已经取消
            } else {
                $e->status = Carbon::now()->isBefore(Carbon::parse($e->starttime)) ? 3 : 4; // 3=支付成功   4=已完成
            }
            return $e;
        }, $orders);

        $this->success('ok', $orders);

    }

    public function getUserInfo()
    {
        $userId = $this->auth->getUser()->id;

        $user = \app\admin\model\User::get($userId);

        $userExtend = Extend::where('user_id', $userId)->find();
        $money = $userExtend->balance;

        $info = [
            'avatar' => ykxImageUrl($user->avatar),
            'nickname' => $user->nickname,
            'gender' => $user->gender ? ($user->gender == 1 ? '男' : '女') : '保密',
            'mobile' => $user->mobile,
            'birthday' => $user->birthday ? $user->birthday : '',
            'balance' => $userExtend->balance,
            'credit_score' => $userExtend->credit_score,
            'is_realname' => $userExtend->is_realname,
            'name' => $userExtend->name,
            'id_card' => $userExtend->id_card,
            'unused_coupon_num' => \app\admin\model\user\Coupon::where('user_id', $userId)->where('is_used', 0)->where('end_time', '>=', Carbon::now()->toDateString())->count(),
            'card_num' => \app\admin\model\user\Card::where('user_id', $userId)->whereExp('total_hour', '> hasconsumedhour')->count(),

        ];

        $this->success('ok', $info);
    }

    public function saveUserInfo()
    {
        $userId = $this->auth->getUser()->id;
        $avatar = $this->request->post('avatar');
        $nickname = $this->request->post('nickname');
        $gender = $this->request->post('gender');
        $mobile = $this->request->post('mobile');
        $birthday = $this->request->post('birthday');

        if ('男' == $gender) {
            $gender = 1;
        } else if ('女' == $gender) {
            $gender = 2;
        } else {
            $gender = 0;
        }

        $user = \app\admin\model\User::get($userId);

        $user->avatar = $avatar;
        $user->nickname = $nickname;
        $user->gender = $gender;
        $user->mobile = $mobile;
        $user->birthday = $birthday;
        $user->save();

        // 保持和$userinfo = $this->auth->getUserinfo()得到的数据一致
        $data = $user->toArray();
        $allowFields = ['id', 'username', 'nickname', 'mobile', 'avatar', 'score'];
        $userinfo = array_intersect_key($data, array_flip($allowFields));

        $this->success('ok', $userinfo);
    }

    public function mpWeixinDecodePhone()
    {

        if ($this->request->isPost()) {

            $user = $this->auth->getUser();

            $encryptedData = $this->request->post('encryptedData');
            $iv = $this->request->post('iv');
            $doSet = $this->request->post('doSet', 0); //是否保存

            $mpAppid = Env::get('mp.appid');
            $mpAppSecret = Env::get('mp.app_secret');

            $config = [
                'app_id' => $mpAppid,
                'secret' => $mpAppSecret,

                'response_type' => 'array',
                'log' => [
                    'level' => 'debug',
                    'file' => __DIR__ . '/wechat.log',
                ],
            ];

            try {
                $app = Factory::miniProgram($config);

                $sessionkey = Third::where('user_id', $user->id)->find()->sessionkey;

                $decryptedData = $app->encryptor->decryptData($sessionkey, $iv, $encryptedData);

                if ($doSet) {
                    $user->mobile = $decryptedData['phoneNumber'];
                    $user->save();
                }

            } catch (\Exception $e) {

                $this->error($e->getMessage(), null, 401);
            }

            $this->success('ok', ['phone' => $decryptedData['phoneNumber']]);
        }
    }


    public function mpWeixinGetPhone()
    {

        if ($this->request->isPost()) {

            $user = $this->auth->getUser();

            $code = $this->request->post('code');
            $doSet = $this->request->post('doSet', 0); //是否保存

            $mpAppid = Env::get('mp.appid');
            $mpAppSecret = Env::get('mp.app_secret');

            $config = [
                'app_id' => $mpAppid,
                'secret' => $mpAppSecret,

                'response_type' => 'array',
                'log' => [
                    'level' => 'debug',
                    'file' => __DIR__ . '/wechat.log',
                ],
            ];

            try {
                $app = Factory::miniProgram($config);
                $accessToken = $app->access_token->getToken()['access_token'];

                $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$accessToken";

                $headers = ['content-type:application/json'];
                $options = [
                    CURLOPT_HTTPHEADER => $headers
                ];

                $postdata = [
                    'code' => $code,
                ];

                $res = Http::post($url, json_encode($postdata), $options);
                $res = json_decode($res, true);
                if (0 == $res['errcode']) {
                    $phone = $res['phone_info']['phoneNumber'];
                } else {
                    throw new \Exception($res['errmsg']);
                }

                if ($doSet) {
                    $user->mobile = $phone;
                    $user->save();
                }

            } catch (\Exception $e) {

                $this->error($e->getMessage());
            }

            $this->success('ok', ['phone' => $phone]);
        }
    }



    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function applyCooperation()
    {
        $postData = $this->request->post();
        try {
            Apply::create($postData);
            $this->success('提交成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function applySuggestion()
    {
        $postData = $this->request->post();
        try {
            Suggestion::create($postData);
            $this->success('提交成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function getUserAllCoupon()
    {
        $userId = $this->auth->getUser()->id;
        $coupons = \app\admin\model\user\Coupon::where('user_id', $userId)->order('id', 'desc')->select();
        $this->success('ok', $coupons);
    }

    public function getUserUnusedCoupon()
    {
        $userId = $this->auth->getUser()->id;
        $coupons = \app\admin\model\user\Coupon::where('user_id', $userId)
            ->where('is_used', 0)
            ->where('start_time', '<=', Carbon::now()->toDateString())
            ->where('end_time', '>=', Carbon::now()->toDateString())
            ->select();
        $data = array_map(function ($e) {
            return [
                'id' => $e->id,
                'name' => $e->coupon_name,
                'price' => $e->reduce_price,
                'min_price' => $e->min_price,
                'starttime' => $e->start_time,
                'endtime' => $e->end_time,
            ];
        }, $coupons);
        $this->success('ok', $data);
    }

    public function getUserAllReservation()
    {
        $userId = $this->auth->getUser()->id;
        $reserves = \app\admin\model\Reserve::with(['store', 'room'])->where('user_id', $userId)->order('id', 'desc')->select();
        $reserves = array_map(function ($e) {
            return [
                'id' => $e->id,
                'store_name' => $e->store->store_name ?? '-',
                'store_bannerimage' => $e->store ? cdnurl($e->store->store_bannerimage, true) : '',
                'room_name' => $e->room->room_name,
                'price' => $e->fee,
                'pay_way' => $e->pay_way,
                'startime' => $e->starttime,
                'endtime' => $e->endtime,
                'createtime' => $e->createtime,
                'order_num' => $e->trade_no,
                're_status' => $e->re_status,
                'card_id' => $e->card_id,
                'card_name' => (function($cardId){
                    if (is_numeric($cardId)) {
                        return \app\admin\model\user\Card::get($cardId)->name;
                    } else {
                        return null;
                    }
                })($e->card_id),
            ];
        }, $reserves);

        $this->success('ok', $reserves);
    }

    public function checkNameAndIdCard()
    {
        if ($this->request->isPost()) {
            $name = $this->request->post('name', '');
            $idCard = $this->request->post('id_card', '');
            // 如果验证通过后记录信息
            $userId = $this->auth->getUser()->id;
            $userExtend = Extend::where('user_id', $userId)->find();
            if ($userExtend->is_realname == '1') {
                $this->error('不能重复实名', []);
            }

            $faceidLib = new FaceIdLib();
            $checkRes = $faceidLib->checkNameAndIdCard($name, $idCard);

            $msg = $checkRes['msg'];
            $data = $checkRes['data'];

            if ($msg != 'ok') {
                $this->error($msg, $data);
            }
            if ($userExtend) {
                $userExtend->name = $name;
                $userExtend->id_card = $idCard;
                $userExtend->is_realname = 1;
                $userExtend->save();
                // 更新user表
                $user = \app\common\model\User::get($userId);
                $user->birthday = date('Y-m-d', strtotime(substr($idCard, 6, 8)));
                $user->save();
            }
            $this->success('实名成功', $data);
        }

        $this->error('need post method');
    
    }

    public function getCreditLogs()
    {
        $logs = (new CreditLib())->getLogs($this->auth->getUser()->id);
        $this->success('ok', $logs);
    }


}
